<template>
  <div class="component-distribution-prod-add-or-update">
    <el-dialog
      v-model="visible"
      :title="!dataForm.distributionProdId ? '新增分销商品' : $t('seckill.view')"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        :label-width="$t('language') === 'language' ? '130px' : '90px'"
        :disabled="true"
        @submit.prevent
        @keyup.enter="onSubmit ()"
      >
        <el-form-item :label="$t('groups.relatedProducts')">
          <div v-if="prodData[0]!=null">
            <el-card
              :body-style="{ padding: '0px' }"
              style="height: 160px;width: 120px"
            >
              <prod-pic
                height="104px"
                width="100%"
                :pic="prodData[0].pic"
              />
              <div class="card-prod-bottom">
                <span class="card-prod-name">{{ prodData[0].prodName }}</span>
              </div>
            </el-card>
          </div>
          <div
            v-if="prodData[0]==null"
            class="default-btn"
            @click="addProd"
          >
            {{ $t('product.select') }}
          </div>
        </el-form-item>
        <div v-if="dataForm.defaultReward === 0">
          <el-form-item
            :label="$t('marketing.rewardRatio')"
            prop="awardType"
          >
            <el-radio-group v-model="dataForm.awardProportion">
              <el-radio :label="0">
                {{ $t('marketing.proporteward') }}
              </el-radio>
              <el-radio :label="1">
                {{ $t('marketing.rewardByFixedValue') }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            :label="$t('marketing.inviterReward')"
            prop="awardType"
          >
            <el-radio-group v-model="dataForm.parentAwardSet">
              <el-radio :label="0">
                {{ $t('seckill.close') }}
              </el-radio>
              <el-radio :label="1">
                {{ $t('seckill.open') }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            :label=" dataForm.awardNumberSet === 1 ? $t('marketing.amountSetting') : $t('marketing.defaultReward')"
            prop="awardType"
          >
            <div v-if="dataForm.awardNumberSet === 0">
              <el-input
                v-model="dataForm.awardNumbers"

                :precision="2"
                :min="0"
                style="width:200px"
              >
                <template #append>
                  <span v-if="dataForm.awardProportion === 1">{{ $t('distribution.dbcTip2') }}</span>
                  <span v-else>%</span>
                </template>
              </el-input>

              <span
                v-if="dataForm.parentAwardSet === 1"
              >&nbsp; {{ $t('marketing.inviterRewardAmount') }}:</span>
              <el-input
                v-if="dataForm.parentAwardSet === 1"
                v-model="dataForm.parentAwardNumbers"
                :precision="2"
                :min="0"

                style="width:200px"
              >
                <template #append>
                  <span v-if="dataForm.awardProportion === 1">{{ $t('distribution.dbcTip2') }}</span>
                  <span v-else>%</span>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </div>
        <el-form-item
          :label="$t('product.status')"
          prop="state"
        >
          <el-radio-group v-model="dataForm.state">
            <el-radio :label="1">
              {{ $t('prodList.onShelf') }}
            </el-radio>
            <el-radio :label="0">
              {{ $t('prodList.offShelf') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn"
            @click="visible = false"
          >
            {{ $t('seckill.close') }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addProdVisible"
      ref="addProdRef"
      @refresh-discount-prods="selectDiscountProds"
    />
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import AddOrUpdate from './discountProd-add-or-update.vue'

const emit = defineEmits(['refreshDataList'])
const dataForm = ref({
  prodId: 0,
  distributionAmount: 0,
  awardId: 0,
  state: 1,
  defaultReward: 0,
  awardProportion: 0,
  awardNumberSet: 0,
  awardNumbers: '',
  parentAwardNumbers: '',
  parentAwardSet: 0
})
const levelData = ref([])
const prodData = ref([])
const visible = ref(false)
const dataRule = {}
const distributionProdId = ref(null)

const dataFormRef = ref(null)
const init = (data) => {
  visible.value = true
  if (data) {
    dataForm.value = data
    prodData.value[0] = dataForm.value.product
  } else {
    nextTick(() => {
      dataFormRef.value?.resetFields()
      dataForm.value.defaultReward = 1
      levelData.value = []
      prodData.value = []
      distributionProdId.value = null
    })
  }
}
defineExpose({ init })

const addProdVisible = ref(false)
/**
 * 打开选择商品
 */
const addProd = () => {
  addProdVisible.value = true
  nextTick(() => {
    addProd.value.init(0, prodData.value)
  })
}

/**
 * 商品选择回调
 * @param prods
 */
const selectDiscountProds = (prods) => {
  if (prods) {
    nextTick(() => {
      http({
        url: http.adornUrl('/distribution/distributionProd/count'),
        method: 'get',
        params: http.adornParams({
          prodId: prods[0].prodId
        })
      })
        .then(({ data }) => {
          if (data === 0) {
            dataForm.value.prodId = prods[0].prodId
            prodData.value[0] = prods[0]
          } else {
            ElMessage({
              message: '该商品已经在分销商品列表中',
              type: 'warning'
            })
          }
        })
    })
  }
}

/**
 * 表单提交
 */
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (dataForm.value.awardNumberSet === 1) {
        // 创建json存入奖励表
        const awardNumberjson = []
        const parentAwardNumberjson = []
        levelData.value.forEach((item) => {
          awardNumberjson.push(Number.parseFloat(item.awardNumber).toFixed(2))
          parentAwardNumberjson.push(Number.parseFloat(item.parentAwardNumber).toFixed(2))
        })
        dataForm.value.awardNumbers = JSON.stringify(awardNumberjson)
        dataForm.value.parentAwardNumbers = JSON.stringify(parentAwardNumberjson)
      }
      const param = dataForm.value

      http({
        url: http.adornUrl('/distribution/distributionProd'),
        method: param.distributionProdId ? 'put' : 'post',
        data: http.adornData(param)
      })
        .then(() => {
          ElMessage({
            message: $t('remindPop.success'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              visible.value = false
              emit('refreshDataList')
            }
          })
        })
    }
  })
}
</script>
